package com.sky.zzh.adapter;

import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.sky.zzh.R;
import com.sky.zzh.util.UserInfoManager;

public class DeviceAdapter extends BaseAdapter {
	private Context context;

	private JSONArray jsonArray;

	HashMap<Integer, View> lmap = new HashMap<Integer, View>();

	public void setJsonArray(JSONArray jsonArray) {
		this.jsonArray = jsonArray;
		notifyDataSetChanged();
	}

	public DeviceAdapter(Context context) {
		super();
		this.context = context;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return jsonArray == null ? 0 : jsonArray.length();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(int pos, View convertView, ViewGroup arg2) {
		// TODO Auto-generated method stub
		ViewHolder holder = null;
		if (lmap.get(pos) == null) {
			convertView = LayoutInflater.from(context).inflate(R.layout.item_device, null);
			holder = new ViewHolder();
			holder.tvName = (TextView) convertView.findViewById(R.id.tv_device_name);
			holder.ivImage = (ImageView) convertView.findViewById(R.id.iv_select);
			lmap.put(pos, convertView);
			convertView.setTag(holder);
		} else {
			convertView = lmap.get(pos);
			holder = (ViewHolder) convertView.getTag();
		}

		try {
			holder.tvName.setText(jsonArray.getJSONObject(pos).getString("Description"));
			if ("True".equals(jsonArray.getJSONObject(pos).getString("IsActivated"))) {
				holder.ivImage.setVisibility(View.VISIBLE);
				UserInfoManager.getInstance().setUUID(jsonArray.getJSONObject(pos).getString("UUID"));
				UserInfoManager.getInstance().sync(context, true);
			}else{
				holder.ivImage.setVisibility(View.GONE);
			}
//			if(UserInfoManager.getInstance().getUUID().equals(jsonArray.getJSONObject(pos).getString("UUID"))){
//				holder.ivImage.setVisibility(View.VISIBLE);
//			}else{
//				holder.ivImage.setVisibility(View.GONE);
//			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return convertView;
	}

	private static class ViewHolder {
		private TextView tvName;
		private ImageView ivImage;
	}
}
